@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<div class="container-fluid">
    <el-card shadow="hover">
        <template #header>
            <el-row :gutter="20">
                <el-col :span="16">
                    <span style="font-size: 18px; font-weight: bold;">批量记录体重</span>
                </el-col>
                <el-col :span="8" class="text-right">
                    <el-button type="default" @@click="goBack" icon="el-icon-arrow-left" size="small">返回列表</el-button>
                    <el-button type="info" @@click="goDashboard" icon="el-icon-data-line" size="small" style="margin-left: 10px;">数据分析</el-button>
                </el-col>
            </el-row>
        </template>

        <el-form ref="batchRecordForm">
            <el-row :gutter="20" style="margin-bottom: 20px;">
                <el-col :span="8">
                    <el-form-item label="开始日期" prop="startDate">
                        <el-date-picker v-model="startDate"
                                        type="date"
                                        placeholder="选择开始日期"
                                        value-format="yyyy-MM-dd"
                                        style="width: 100%;"></el-date-picker>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="结束日期" prop="endDate">
                        <el-date-picker v-model="endDate"
                                        type="date"
                                        placeholder="选择结束日期"
                                        value-format="yyyy-MM-dd"
                                        style="width: 100%;"></el-date-picker>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item>
                        <el-button type="primary" @@click="generateRecordRows" style="width: 100%; margin-top: 20px;">生成记录行</el-button>
                    </el-form-item>
                </el-col>
            </el-row>

            <div style="overflow-x: auto;">
                <el-table :data="records" style="width: 100%;">
                    <el-table-column prop="date" label="日期" width="120"></el-table-column>
                    <el-table-column prop="meridiem" label="时段" width="100">
                        <template slot-scope="scope">
                            <el-select v-model.number="scope.row.meridiem" placeholder="选择时段">
                                <el-option label="早晨" value="1"></el-option>
                                <el-option label="中午" value="2"></el-option>
                                <el-option label="晚上" value="3"></el-option>
                                <el-option label="其他" value="4"></el-option>
                            </el-select>
                        </template>
                    </el-table-column>
                    <el-table-column prop="weighKg" label="体重(KG)" width="120">
                        <template slot-scope="scope">
                            <el-input-number v-model.number="scope.row.weighKg"
                                             :step="0.1"
                                             :min="20"
                                             :max="300"
                                             placeholder="体重"
                                             style="width: 100%;"></el-input-number>
                        </template>
                    </el-table-column>
                    <el-table-column prop="bodyFat" label="体脂率(%)" width="120">
                        <template slot-scope="scope">
                            <el-input-number v-model.number="scope.row.bodyFat"
                                             :step="0.1"
                                             :min="5"
                                             :max="60"
                                             placeholder="体脂率"
                                             style="width: 100%;"></el-input-number>
                        </template>
                    </el-table-column>
                    <el-table-column prop="muscleMass" label="肌肉量(kg)" width="120">
                        <template slot-scope="scope">
                            <el-input-number v-model.number="scope.row.muscleMass"
                                             :step="0.1"
                                             :min="10"
                                             :max="200"
                                             placeholder="肌肉量"
                                             style="width: 100%;"></el-input-number>
                        </template>
                    </el-table-column>
                    <el-table-column prop="remark" label="备注">
                        <template slot-scope="scope">
                            <el-input v-model="scope.row.remark" placeholder="可选"></el-input>
                        </template>
                    </el-table-column>
                </el-table>
            </div>

            <div style="margin-top: 20px; text-align: center;">
                <el-button type="success"
                           @@click="saveBatchRecords"
                           :loading="isSaving"
                           size="large"
                           icon="el-icon-check">
                    {{ isSaving ? '保存中...' : '批量保存' }}
                </el-button>
            </div>
        </el-form>
    </el-card>
</div>

@section Scripts {
    <script>
            var batchRecordApp = new Vue({
                    el: '#app',
                    mixins: [curdMixin],
            data: {
                startDate: '',
                endDate: '',
                records: [],
                isSaving: false,
                form: {},
                rules: {
                    startDate: [
                        { required: true, message: '请选择开始日期', trigger: 'change' }
                    ],
                    endDate: [
                        { required: true, message: '请选择结束日期', trigger: 'change' }
                    ]
                }
            },
            methods: {
                formatDate: function(date) {
                    const year = date.getFullYear();
                    const month = String(date.getMonth() + 1).padStart(2, '0');
                    const day = String(date.getDate()).padStart(2, '0');
                    return `${year}-${month}-${day}`;
                },
                generateRecordRows: function() {
                    this.$refs.batchRecordForm.validate((valid) => {
                        if (!valid) {
                            return false;
                        }

                        const startDate = new Date(this.startDate);
                        const endDate = new Date(this.endDate);

                        if (startDate > endDate) {
                            this.$message.error('开始日期不能晚于结束日期！');
                            return;
                        }

                        // 计算日期范围（最多30天）
                        const days = Math.ceil((endDate - startDate) / (1000 * 60 * 60 * 24)) + 1;
                        if (days > 30) {
                            this.$message.error('日期范围不能超过30天！');
                            return;
                        }

                        // 清空现有记录
                        this.records = [];

                        // 循环生成每一天的记录
                        const currentDate = new Date(startDate);
                        while (currentDate <= endDate) {
                            const dateStr = this.formatDate(currentDate);

                            this.records.push({
                                date: dateStr,
                                meridiem: 1, // 默认早晨
                                weighKg: '',
                                bodyFat: '',
                                muscleMass: '',
                                remark: ''
                            });

                            // 移动到下一天
                            currentDate.setDate(currentDate.getDate() + 1);
                        }

                        this.$message.success(`已生成 ${days} 条记录行！`);
                    });
                },
                saveBatchRecords: function() {
                    // 收集有效记录
                    const records = [];
                    let validRecords = 0;

                    this.records.forEach(record => {
                        if (record.weighKg) {
                            const weighRecord = {
                                weighTime: new Date(record.date + 'T08:00:00'), // 默认8点
                                weighKg: parseFloat(record.weighKg),
                                meridiem: record.meridiem,
                                remark: record.remark
                            };

                            // 添加体脂率（如果有）
                            if (record.bodyFat) {
                                weighRecord.bodyFat = parseFloat(record.bodyFat);
                            }

                            // 添加肌肉量（如果有）
                            if (record.muscleMass) {
                                weighRecord.muscleMass = parseFloat(record.muscleMass);
                            }

                            records.push(weighRecord);
                            validRecords++;
                        }
                    });

                    if (records.length === 0) {
                        this.$message.warning('请至少填写一条有效记录！');
                        return;
                    }

                    // 确认保存
                    this.$confirm('确认保存？', '提示', {
                        confirmButtonText: '确认保存',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        this.sendBatchSaveRequest(records);
                    }).catch(() => {
                        this.$message.info('已取消保存');
                    });
                },
                sendBatchSaveRequest: function(records) {
                    this.isSaving = true;

                    this.$http.post('/WeighInfo/batchAdd', records).then(response => {
                        this.isSaving = false;
                        if (response.data.code === 200) {
                            this.$message.success(`成功保存 ${response.data.data?.count || 0} 条记录！`);
                            setTimeout(() => {
                                this.navigateTo('/WeighInfo/Index');
                            }, 1500);
                        } else {
                            this.$message.error(response.data.message || '保存失败！');
                        }
                    }).catch(error => {
                        this.isSaving = false;
                        this.$message.error('保存失败，请稍后重试！');
                        console.error('保存失败:', error);
                    });
                },
                navigateTo: function(url) {
                    window.location.href = url;
                },
                goBack: function() {
                    this.navigateTo('/WeighInfo/Index');
                },
                goDashboard: function() {
                    this.navigateTo('/WeighInfo/Dashboard');
                }
            },
            mounted: function() {
                // 设置默认日期范围（最近7天）
                const today = new Date();
                const lastWeek = new Date(today);
                lastWeek.setDate(today.getDate() - 7);

                this.startDate = this.formatDate(lastWeek);
                this.endDate = this.formatDate(today);
            }
        });
    </script>
}